<!--
 * @Descripttion:
 * @Author: zhangchong zc16607@gmail.com
 * @Date: 2022-12-30 10:25:40
 * @LastEditors: zhangchong zc16607@gmail.com
 * @LastEditTime: 2023-05-31 16:40:54
-->
<template>
  <div class="w-full h-full flex justify-center">
    <div class="px-5 w-full">
        <div v-show="!terminalVisible">
          <div title="打包配置" class="w-[20px] h-[20px] absolute top-5 right-5 cursor-pointer transition-transform hover:rotate-[90deg] hover:scale-105" @click="() => router.push('/setting')">
            <el-icon :size="20">
              <ep-setting />
            </el-icon>
          </div>
          <div class="flex my-4">
            <p class="text-lg font-bold w-[100px]">目标环境</p>
            <el-select class="w-[300px]" v-model="targetEnv">
              <el-option label="测试环境" value="test"></el-option>
              <el-option label="培训环境" value="train"></el-option>
              <el-option label="正式环境" value="prod"></el-option>
            </el-select>
          </div>
          <div class="flex my-4">
            <p class="text-lg font-bold w-[100px]">压缩包名</p>
            <el-input class="!w-[300px]" v-model="packageName"></el-input>
          </div>

          <div class="flex my-4">
          <p class="text-lg font-bold w-[100px] shrink-0">项目列表</p>
              <el-scrollbar class="!h-[400px]">
                <div >
                  <el-checkbox-group v-model="checkedList">
                    <el-row>
                      <el-col class="group flex items-center" :span="12" v-for="(item, i) in filterProject" :key="i">
                        <el-checkbox size="large" class="check-item" :label="item" />
                        <el-icon title="隐藏此项目" class="group-hover:!block !hidden ml-2 cursor-pointer hover:!text-[#409eff] !text-[#737373]" @click="hiddenProject(item)" :size="20">
                          <ep-close />
                        </el-icon>
                      </el-col>
                    </el-row>
                  </el-checkbox-group>
                  <div v-if="hiddenedProArr.length" class="text-center text-[#409eff] my-5">
                    <el-link :underline="false" @click="hiddenedProArr=[]">显示所有项目</el-link>
                  </div>
                </div>
              </el-scrollbar>
          </div>
        </div>

        <!-- 终端输出日志 -->
        <el-scrollbar class="!h-[512px] bg-slate-800 rounded-md" ref="scrollbarRef" v-show="terminalVisible">
          <div ref="xtermRef" class="terminal-wrap text-[#f7f7f7]"></div>
        </el-scrollbar>

 
      <div class=" text-center mt-4">
        <div class="w-2/5 mx-auto my-5 flex" :style="{visibility: buildStatus ? 'visible': 'hidden'}">
          <el-progress :stroke-width="10" :class="{'w-full': true, 'progress-bar-striped': true, 'progress-bar-animated': !(percent === 0 || percent === 100) ? true : false}" :percentage="percent"></el-progress>
          <el-link class="whitespace-nowrap" :underline="false" v-if="!terminalVisible" @click="terminalVisible = true">详细信息</el-link>
          <el-link class="whitespace-nowrap" :underline="false" v-else @click="terminalVisible = false">关闭详情</el-link>
        </div>
        <el-button :disabled="!(percent === 0 || percent === 100)" size="large" type="primary" @click="build">
          {{(percent === 0 || percent === 100) ? '开始打包' : '打包中'}}
        </el-button>
      </div>
      
    </div>


  </div>
</template>

<script setup>
import {computed, nextTick, onMounted, ref, watch, watchEffect, onBeforeUnmount} from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()


const projectList = ref(['aeotrade_admin', 'aeotrade_container', 'aeotrade_openPlatform'])
const checkedList = ref([])
const targetEnv = ref('test')
const packageName = ref('')
const hiddenedProArr = ref([])
const config = ref(null)
const buildStatus = ref(false)
const terminalVisible = ref(false)
const xtermRef = ref(null)
const scrollbarRef = ref(null)
const percent = ref(0)

const filterProject = computed(() => projectList.value.filter(item => !hiddenedProArr.value.includes(item)))




const cubic = value => Math.pow(value, 3)
const easeInOutCubic = value => value < 0.5 ? cubic(value * 2) / 2 : 1 - cubic((1 - value) * 2) / 2


onMounted(() => {
  checkedList.value = JSON.parse(localStorage.getItem('checkedList') || '[]')
  targetEnv.value = localStorage.getItem('targetEnv') || 'test'
  packageName.value = localStorage.getItem('packageName') || '冲刺xx'
  hiddenedProArr.value = JSON.parse(localStorage.getItem('hiddenedProArr') || '[]')
  // 过滤checkdList，必须要在总列表内
  
  const stConfig = JSON.parse(localStorage.getItem('config') || '{}')
  if(!stConfig || !stConfig.rootDir || !stConfig.outputDir) router.push('/setting')
  config.value = stConfig
 
  // 获取项目列表
  try{
    window.$api.getCurrentDir(stConfig.rootDir.join('/') + '/').then(dirArr => {
      projectList.value = dirArr.filter(dir => !dir.startsWith('.'))
    })
  }catch(e){
    console.log('err', e)
    router.push('/setting')
  }

  window.$listen.buildInfo(listenBuildCallback)
  window.$listen.percent(listenPercentCallback)

})

onBeforeUnmount(() => {
  window.$cancelListen.buildInfo()
  window.$cancelListen.percent()
})

const listenBuildCallback = (event, data) => {
  console.log('dd', data)
  data = data.replace(/ /g, '\u00a0')
  // data = data.replace(/\n/g, '<br>')
  const div = document.createElement('div')
  div.innerText = data
  xtermRef.value.appendChild(div)
  
  const endValue = xtermRef.value.clientHeight - 512
  const startValue = scrollbarRef.value.wrapRef.scrollTop
  const beginTime = Date.now()
  const frameFunc = () => {
    const progress = (Date.now() - beginTime) / 700
    if (progress < 1) {
      scrollbarRef.value.setScrollTop(startValue + endValue * easeInOutCubic(progress))
      requestAnimationFrame(frameFunc)
    } else {
      scrollbarRef.value.setScrollTop(xtermRef.value.clientHeight - 512)
    }
  }
  requestAnimationFrame(frameFunc)
}


const listenPercentCallback = (event, per) => {
  percent.value = parseInt(per)
}



 watch([() => checkedList.value, () => targetEnv.value, () => packageName.value, () => hiddenedProArr.value.length],
  () => {
  localStorage.setItem('checkedList', JSON.stringify(checkedList.value))
  localStorage.setItem('targetEnv', targetEnv.value)
  localStorage.setItem('packageName', packageName.value)
  localStorage.setItem('hiddenedProArr', JSON.stringify(hiddenedProArr.value))
 })

 // 开始打包
 const build = () => {
  xtermRef.value && xtermRef.value.replaceChildren && xtermRef.value.replaceChildren()
  
  let buildInfo = {
    ...config.value,
    project: [...checkedList.value],
    env: targetEnv.value,
    name: packageName.value
  }
  buildInfo.rootDir = buildInfo.rootDir.join('/') + '/'
  buildInfo.outputDir = buildInfo.outputDir.join('/') + '/'

  window.$api.build(buildInfo)

  // 打包状态
  buildStatus.value = true
 }

 const hiddenProject = (item) => {
  hiddenedProArr.value.push(item)
  if(checkedList.value.includes(item)){
    checkedList.value = checkedList.value.filter(checked => !checked.includes(item))
  }
 }
</script>


<style scoped>
.check-item{
  display: block;
  line-height: 40px;
}
.check-item :deep(.el-checkbox__label){
  font-size: 16px;
}
.check-item :deep(.el-checkbox__input){
  transform: translateY(2px);
}
.progress-bar-striped :deep(.el-progress-bar__inner){
  background-image: linear-gradient(135deg,rgba(255,255,255,.3) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.3) 50%,rgba(255,255,255,.3) 75%,transparent 75%,transparent);
  background-size: 0.75rem 0.75rem;
}
@keyframes el-progress-bar__inner {
  from { background-position: 0 0; }
  to { background-position: 0.75rem 0; }
}
.progress-bar-animated :deep(.el-progress-bar__inner){
  animation: 1.5s linear infinite el-progress-bar__inner;
  animation-duration: 1.5s!important;
}
</style>